package com.ibeetl.admin.aod.service.excel.processor.data;

import com.ibeetl.admin.aod.entity.DieImportTask;
import com.ibeetl.admin.aod.service.DieImportTaskService;
import com.ibeetl.admin.aod.service.excel.match.MatchManagerImpl;
import com.ibeetl.admin.aod.service.excel.task.ExcelCompareTask;
import com.ibeetl.admin.core.entity.CoreUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 配对管理处理器
 */
@Component
public class AodIndustryDataExcelCompareProcessor extends AbstractDataProcessor {

    @Autowired
    protected MatchManagerImpl matchManager;

    @Autowired
    protected DieImportTaskService dieImportTaskService;

    public void process(MultipartFile[] files, CoreUser coreUser) throws Exception {

        if (null == files) {
            throw new Exception("未上传文件,请重新上传文件");
        }
        if (files.length != 2) {
            throw new Exception("最多只能上传2个文件,请重新上传文件");
        }

        List<File> needProcessFileList = matchManager.convertMultipartFileList2FileList(Arrays.asList(files));

        String batchNo = saveNewTask(getFileName(needProcessFileList), needProcessFileList.get(0).getParent(), coreUser);

        executorService.submit(new ExcelCompareTask(needProcessFileList, batchNo, matchManager));

    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    private String saveNewTask(String fileName, String fileSavePath, CoreUser coreUser) {
        String batchNo = matchManager.getBatchNo();
        DieImportTask dieImportTask = new DieImportTask();
        dieImportTask.setBatchNo(batchNo);
        dieImportTask.setImportType(DieImportTask.ImportType.MATCH_DATA_UPLOAD.getValue());
        dieImportTask.setFileName(fileName);
        dieImportTask.setFileSavePath(fileSavePath);
        dieImportTask.setProcessStatus(DieImportTask.ProcessStatus.TO_BE_PROCESSED.getValue());
        dieImportTask.setPhysicsFlag(DieImportTask.NORMAL);
        dieImportTask.setCreateUser(coreUser.getName());
        dieImportTask.setCreateTime(new Date());
        dieImportTaskService.save(dieImportTask);
        return batchNo;
    }

    private String getFileName(List<File> fileList) {
        StringBuilder fileName = new StringBuilder();
        for (File file : fileList) {
            fileName.append(file.getName() + ",");
        }
        return fileName.toString();
    }

}
